const db = require('../db/index');

const RunSql = async (sql, val) => {
  return new Promise(resolve => {
    db.query(sql, val, (err, result) => {
      if (err) return err;
      resolve(result)
    })
  })
}

exports.changeHeadPicture = async (req, res) => {
  const file = req.file;
  let filePathName = `http://127.0.0.1:8081/${file.filename}`
  const user = req.auth;
  const selectSql = 'select * from bl_users where username=?'
  let selectResult = await RunSql(selectSql, user.username);
  if (selectResult.length == 0 || selectResult[0].is_delete == 1) return res.cc('此用户不存在');
  const updateSql = 'update bl_users set use_pict=? where username=?'
  let insertResult = await RunSql(updateSql, [filePathName, user.username]);
  if (insertResult.affectedRows == 1) {
    res.cc('头像修改成功', 200, {
      imgPath: filePathName
    })
  } else {
    return res.cc(insertResult)
  }
}

exports.getHeadPicture = async (req, res) => {
  const user = req.auth;
  const selectSql = 'select * from bl_users where username=?'
  let selectResult = await RunSql(selectSql, user.username);
  if (selectResult.length == 0 || selectResult[0].is_delete == 1) return res.cc('此用户不存在');
  return res.cc('获取成功', 200, selectResult);
}

exports.changePassword = async (req, res) => {
  let bodyData = req.body;
  const updateSql = 'update bl_users set password=? where password=? and username=?'
  let updataResult = await RunSql(updateSql, [bodyData.newPassword, bodyData.oldPassword, req.auth.username]);
  if (updataResult.affectedRows == 1) {
    return res.cc('密码更换成功', 200);
  } else {
    return res.cc('请确保旧密码输入正确');
  }

}

exports.changeBgImg = async (req, res) => {
  const file = req.file;
  const user = req.auth;
  let filePathName = `http://127.0.0.1:8081/${file.filename}`;
  const updateSql = 'update bl_users set bg_pict=? where username=?'
  let insertResult = await RunSql(updateSql, [filePathName, user.username]);
  if (insertResult.affectedRows == 1) {
    res.cc('背景修改成功', 200, {
      imgPath: filePathName
    })
  } else {
    return res.cc(insertResult)
  }
}
